import json
import os
from datetime import datetime
from dataclasses import dataclass, asdict
from typing import Dict, List, Optional

@dataclass
class QuestionStats:
    """题目统计"""
    question_id: str
    review_count: int = 0
    correct_count: int = 0
    wrong_count: int = 0
    last_review_date: Optional[str] = None
    wrong_steps: List[int] = None  # 记录错误的步骤
    mastery_level: float = 0.0  # 掌握程度 0-1
    tags: Dict = None  # 知识点标签

@dataclass
class LearningStats:
    """学习统计"""
    total_questions: int = 0
    total_reviews: int = 0
    total_correct: int = 0
    total_wrong: int = 0
    average_mastery: float = 0.0
    knowledge_stats: Dict[str, Dict] = None  # 知识点统计
    difficulty_stats: Dict[str, Dict] = None  # 难度统计
    question_stats: Dict[str, QuestionStats] = None  # 题目统计
    last_update: Optional[str] = None

class LearningStatsManager:
    def __init__(self, stats_file: str = "learning_stats.json"):
        self.stats_file = stats_file
        self.stats = self._load_stats()
    
    def _load_stats(self) -> LearningStats:
        """加载学习统计"""
        if os.path.exists(self.stats_file):
            try:
                with open(self.stats_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    # 转换题目统计
                    if 'question_stats' in data:
                        data['question_stats'] = {
                            qid: QuestionStats(**stats)
                            for qid, stats in data['question_stats'].items()
                        }
                    return LearningStats(**data)
            except Exception as e:
                print(f"加载学习统计失败: {e}")
        return LearningStats(
            knowledge_stats={},
            difficulty_stats={},
            question_stats={}
        )
    
    def _save_stats(self):
        """保存学习统计"""
        try:
            # 更新最后更新时间
            self.stats.last_update = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            
            # 转换为字典
            data = asdict(self.stats)
            
            # 保存到文件
            with open(self.stats_file, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存学习统计失败: {e}")
    
    def update_question_stats(self, question_id: str, is_correct: bool, wrong_steps: List[int] = None):
        """更新题目统计"""
        # 获取或创建题目统计
        if question_id not in self.stats.question_stats:
            self.stats.question_stats[question_id] = QuestionStats(question_id=question_id)
        
        stats = self.stats.question_stats[question_id]
        
        # 更新统计
        stats.review_count += 1
        if is_correct:
            stats.correct_count += 1
        else:
            stats.wrong_count += 1
            if wrong_steps:
                stats.wrong_steps = wrong_steps
        
        # 更新最后复习时间
        stats.last_review_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        # 计算掌握程度
        if stats.review_count > 0:
            stats.mastery_level = stats.correct_count / stats.review_count
        
        # 更新总体统计
        self.stats.total_reviews += 1
        if is_correct:
            self.stats.total_correct += 1
        else:
            self.stats.total_wrong += 1
        
        # 保存统计
        self._save_stats()
    
    def update_knowledge_stats(self, question_id: str, tags: List[str]):
        """更新知识点统计"""
        if not tags:
            return
            
        # 更新题目统计中的标签
        if question_id in self.stats.question_stats:
            self.stats.question_stats[question_id].tags = {"knowledge_tags": tags}
        
        # 更新知识点统计
        for tag in tags:
            if tag not in self.stats.knowledge_stats:
                self.stats.knowledge_stats[tag] = {
                    "total": 0,
                    "correct": 0,
                    "wrong": 0,
                    "mastery": 0.0
                }
            
            stats = self.stats.knowledge_stats[tag]
            stats["total"] += 1
            
            # 获取题目统计
            if question_id in self.stats.question_stats:
                q_stats = self.stats.question_stats[question_id]
                if q_stats.correct_count > 0:
                    stats["correct"] += 1
                else:
                    stats["wrong"] += 1
                
                # 更新掌握程度
                if stats["total"] > 0:
                    stats["mastery"] = stats["correct"] / stats["total"]
        
        # 保存统计
        self._save_stats()
    
    def update_difficulty_stats(self, question_id: str, difficulty: int):
        """更新难度统计"""
        difficulty_key = f"level_{difficulty}"
        
        # 更新难度统计
        if difficulty_key not in self.stats.difficulty_stats:
            self.stats.difficulty_stats[difficulty_key] = {
                "total": 0,
                "correct": 0,
                "wrong": 0,
                "mastery": 0.0
            }
        
        stats = self.stats.difficulty_stats[difficulty_key]
        stats["total"] += 1
        
        # 获取题目统计
        if question_id in self.stats.question_stats:
            q_stats = self.stats.question_stats[question_id]
            if q_stats.correct_count > 0:
                stats["correct"] += 1
            else:
                stats["wrong"] += 1
            
            # 更新掌握程度
            if stats["total"] > 0:
                stats["mastery"] = stats["correct"] / stats["total"]
        
        # 保存统计
        self._save_stats()
    
    def get_learning_analysis(self) -> str:
        """获取学习分析报告"""
        if not self.stats.question_stats:
            return "暂无学习记录"
        
        # 计算总体掌握程度
        total_mastery = sum(
            stats.mastery_level
            for stats in self.stats.question_stats.values()
        ) / len(self.stats.question_stats)
        
        # 找出最薄弱的知识点
        weak_knowledge = sorted(
            self.stats.knowledge_stats.items(),
            key=lambda x: x[1]["mastery"]
        )[:3]
        
        # 找出最薄弱的难度级别
        weak_difficulty = sorted(
            self.stats.difficulty_stats.items(),
            key=lambda x: x[1]["mastery"]
        )[:1]
        
        # 生成分析报告
        report = f"""学习分析报告：

1. 总体情况：
   - 总题目数：{self.stats.total_questions}
   - 总复习次数：{self.stats.total_reviews}
   - 正确率：{self.stats.total_correct / self.stats.total_reviews * 100:.1f}%
   - 总体掌握程度：{total_mastery * 100:.1f}%

2. 薄弱知识点：
{chr(10).join(f"   - {tag}：掌握程度 {stats['mastery'] * 100:.1f}%" for tag, stats in weak_knowledge)}

3. 薄弱难度级别：
{chr(10).join(f"   - {diff}：掌握程度 {stats['mastery'] * 100:.1f}%" for diff, stats in weak_difficulty)}

4. 建议：
   - 重点复习薄弱知识点
   - 加强难度级别 {weak_difficulty[0][0]} 的练习
   - 保持每日练习，提高整体掌握程度
"""
        return report 